package com.tyj.tuyijieapp.config.security.password;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * 密码登录
 * </p>
 *
 * @author lhf
 * @since 2020/6/6
 */
@Component
public class PasswordProvider implements AuthenticationProvider {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserDetailsService userDetailsService;
    private static Logger log = LoggerFactory.getLogger(PasswordProvider.class);

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = authentication.getName();
        String password = (String) authentication.getCredentials();
        log.debug("验证码登录");
        UserDetails user = userDetailsService.loadUserByUsername(phone);
        if (user == null) {
            throw new UsernameNotFoundException("用户未找到");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        PasswordToken token = new PasswordToken(authentication.getPrincipal(), authentication.getCredentials(), user.getAuthorities());
        token.setDetails(authentication.getDetails());

        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PasswordToken.class.isAssignableFrom(authentication);
    }
}
